package com.salt.modules.sys.app;

import com.salt.common.config.web.Servlets;
import com.salt.common.json.AjaxJson;
import com.salt.core.log.utils.LoginRecordUtils;
import com.salt.core.redis.utils.CacheUtils;
import com.salt.core.web.BaseController;
import com.salt.modules.log.enums.BusinessStatus;
import com.salt.modules.log.enums.LoginRegisterType;
import com.salt.modules.sys.entity.User;
import com.salt.modules.sys.entity.UserAppDevice;
import com.salt.modules.sys.security.util.JWTUtil;
import com.salt.modules.sys.service.UserAppDeviceService;
import com.salt.modules.sys.service.UserService;
import com.salt.modules.sys.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Objects;

/**
 * 登录Controller
 *
 * @author salt
 * @version 2020-07-31
 */
@RestController
@Api(tags = "移动端登录管理")
@RequestMapping("/app")
public class AppLoginController extends BaseController {

    @Autowired
    private UserAppDeviceService userAppDeviceService;

    /*@PostMapping("/sys/login")
    @ApiOperation("登录接口")
    public AjaxJson login(@RequestParam("userName") String userName,
                          @RequestParam("password") String password) {
        AjaxJson j = new AjaxJson();
        User user = UserUtils.getByLoginName(userName);
        if (user != null && UserService.validatePassword(password, user.getPassword())) {

            if (saltProperites.NO.equals(user.getLoginFlag())){
                j.setSuccess(false);
                j.setMsg("该用户已经被禁止登陆!");
            }else {
                j.setSuccess(true);
                j.put(JWTUtil.TOKEN, JWTUtil.createAccessToken(userName, user.getPassword()));
                j.put(JWTUtil.REFRESH_TOKEN, JWTUtil.createRefreshToken(userName, user.getPassword()));
            }

        } else {
            j.setSuccess(false);
            j.setMsg("用户名或者密码错误!");
        }
        return j;
    }*/


    /*@PostMapping("/sys/login")
    @ApiOperation("登录接口")
    public AjaxJson login(@RequestParam("userName") String userName,
                          @RequestParam("password") String password) {
        AjaxJson j = new AjaxJson();
        User user = UserUtils.getByLoginName(userName);
        boolean loginFlag = false;
        if (StringUtils.isNotBlank(password)) {
            if (user != null && UserService.validatePassword(password, user.getPassword()))
                loginFlag = true;
        } else {
            if (user != null && user.getFreeCode() != null && 1 == user.getFreeCode())
                loginFlag = true;
        }
        if (loginFlag) {
            if (saltProperites.NO.equals(user.getLoginFlag())){
                j.setSuccess(false);
                j.setMsg("该用户已经被禁止登陆!");
            } else {
                j.setSuccess(true);
                j.put(JWTUtil.TOKEN, JWTUtil.createAccessToken(userName, user.getPassword()));
                j.put(JWTUtil.REFRESH_TOKEN, JWTUtil.createRefreshToken(userName, user.getPassword()));
            }
        } else {
            j.setSuccess(false);
            j.setMsg("用户名或者密码错误!");
        }
        return j;
    }*/


    @PostMapping("/sys/login")
    @ApiOperation("登录接口")
    public AjaxJson login(@RequestParam("userName") String userName,
                          @RequestParam("password") String password,
                          @RequestParam(value = "aid", required = false) String aid) {
        AjaxJson j = new AjaxJson();
        User user = UserUtils.getByLoginName(userName);
        boolean loginFlag = false;
        boolean extFlag = false;
        if (StringUtils.isNotBlank(password)) {
            if (user != null && UserService.validatePassword(password, user.getPassword())) {
                loginFlag = true;
                if (StringUtils.isNotBlank(aid))
                    extFlag = true;
            }
        } else {
            if (StringUtils.isNotBlank(aid) && user != null) {
                UserAppDevice userAppDevice = userAppDeviceService.find(user.getId());
                if (userAppDevice != null) {
                    if (Objects.equals(aid, userAppDevice.getDeviceId())) {
                        loginFlag = (1 == userAppDevice.getFreeCode());
                    } else {
                        j.setSuccess(false);
                        j.setMsg("您已更换设备，请使用用户名密码登录!");
                    }
                }
            }
        }
        if (loginFlag) {
            if (saltProperites.NO.equals(user.getLoginFlag())){
                j.setSuccess(false);
                j.setMsg("该用户已经被禁止登陆!");
            } else {
                if (extFlag) {  // 更换设备后用户名密码登录并修改设备ID
                    UserAppDevice userAppDevice = userAppDeviceService.find(user.getId());
                    if (userAppDevice != null && !Objects.equals(aid, userAppDevice.getDeviceId())) {
                        userAppDevice.setDeviceId(aid);
                        userAppDeviceService.updateDeviceId(userAppDevice);
                    }
                }
                j.setSuccess(true);
                j.put(JWTUtil.TOKEN, JWTUtil.createAccessToken(userName, user.getPassword(), user.getName(), user.getId()));
                j.put(JWTUtil.REFRESH_TOKEN, JWTUtil.createRefreshToken(userName, user.getPassword(), user.getName(), user.getId()));

                LoginRecordUtils.senderLog(Servlets.getRequest(), user.getId(), user.getName(), userName, BusinessStatus.SUCCESS.name(), LoginRegisterType.LONGIN.name(), "手机端登陆成功");
            }
        } else {
            j.setSuccess(false);
            j.setMsg("用户名或者密码错误!");
        }
        return j;
    }


    /**
     * 退出登录
     * @throws IOException
     */
    @ApiOperation("用户退出")
    @GetMapping("/sys/logout")
    public AjaxJson logout() {
        AjaxJson j = new AjaxJson();
        String token = UserUtils.getToken();
        if (StringUtils.isNotBlank(token)) {
            User user = UserUtils.getUser();
            CacheUtils.remove(user.getLoginName());
            UserUtils.clearCache();
            UserUtils.getSubject().logout();
            LoginRecordUtils.senderLog(Servlets.getRequest(), user.getId(), user.getName(), user.getLoginName(), BusinessStatus.SUCCESS.name(), LoginRegisterType.LONGIN.name(), "手机端退出成功");
        }
        j.setMsg("退出成功");
        return j;
    }


}
